package com.asset.task;

import com.asset.pojo.Asset;
import com.asset.pojo.AssetDepreciation;
import com.asset.service.AssetService;
import com.asset.service.DepreciationService;
import com.asset.util.PageResult;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 单线程串行执行定时任务
 * @author 11725
 */
@Component
@EnableScheduling
public class Task {

    @Resource
    private DepreciationService deprService;

    @Resource
    private AssetService assetService;

    /**
     * 定时任务，每月 15 号 0 点整进行固定资产折旧
     */
    @Scheduled(cron = "0 0 0 15 1/1 ?")
    public void executeDepreciation() {
        // 1. 分页查询，获取需进行折旧的资产数据
        int pageNum = 1;
        int pageSize = 20;

        int size;
        do {
            PageResult<Asset> pageResult = assetService.selectByDepreciation(pageNum, pageSize);
            // 获取查询结果数
            size = pageResult.getData().size();

            // 2. 计算折旧额，写入折旧记录表
            for (Asset asset : pageResult.getData()) {
                this.createDepreciationRecord(asset);
            }
            pageNum++;
        } while (size == pageSize);
    }

    private void createDepreciationRecord(Asset asset) {
        AssetDepreciation record = new AssetDepreciation();
        // 设置资产编号
        record.setAssetId(asset.getId());
        // 设置折旧日期
        record.setDeprDate(new Date());
        // 设置折旧金额
        BigDecimal totalValue = asset.getPrice().multiply(new BigDecimal(asset.getNumber()));
        BigDecimal deprAmount = totalValue.multiply(asset.getDeprRate());
        record.setDeprAmount(deprAmount);
        // 新增记录
        deprService.insert(record);
    }
}
